package com.wlsk.license.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class CharteredLicenseFilter extends OncePerRequestFilter {

    private static final String REDIRECT_URL = "/noAuthorize";
    private static final String tokenValid = "/checkToken";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (!"/".equals(requestURI) && !REDIRECT_URL.equals(requestURI)) {
            log.info("doFilter url  {}", request.getRequestURI());
        }

        ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper(request);
        String body = parameterRequestWrapper.getBody();
        log.info("body===:{}", body);
        Object object = JSON.parse(body);
        if (!(object instanceof JSONObject)) {
            request.getRequestDispatcher(REDIRECT_URL).forward(request, response);
            return;
        }
        filterChain.doFilter(parameterRequestWrapper, response);
    }
}
